import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:xvideos/assets_tool/images.dart';
import 'package:xvideos/hj_utils/widget_utils.dart';

import '../../assets_tool/app_colors.dart';
import '../../hj_utils/api_service/acg_service.dart';
import '../../hj_utils/api_service/mine_service.dart';
import '../../hj_utils/global.dart';

enum FollowEnum {
  collect, //收藏，加入书架
  cartoon, //动画，加入书架
  actress1, // 女优
  actress2, // 网黄
  user, // 用户
  voiceActor, // 声优
  tag, // 帖子标签
  noval, //小说收藏
}

class FollowButton extends StatefulWidget {
  final String? mediaId; //id
  final FollowEnum? followType; //ui样式
  final bool? isFollow; //
  final Color? borderColor;
  final Function(bool isSuccess)? successsAction; //成功回调

  FollowButton({
    super.key,
    this.mediaId,
    this.followType,
    this.isFollow,
    this.successsAction,
    this.borderColor,
  });

  @override
  State<FollowButton> createState() => _FollowButtonState();
}

class _FollowButtonState extends State<FollowButton> {
  String? get mediaId => widget.mediaId;

  FollowEnum get followType => widget.followType ?? FollowEnum.collect;
  bool get isFollow => widget.isFollow ?? false;
  bool loading = false;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    //1.收藏/加入书架样式
    if (followType == FollowEnum.cartoon) return _buildCollectionView();
    //2.用户关注样式
    if (followType == FollowEnum.actress1 ||
        followType == FollowEnum.actress2 ||
        followType == FollowEnum.user ||
        followType == FollowEnum.voiceActor ||
        followType == FollowEnum.tag) {
      return _buildUserFollowView();
    }
    //3.文字小说收藏
    if (followType == FollowEnum.noval) return _buildNovalCollect();
    return Container();
  }

  //收藏/加入书架样式
  _buildCollectionView() {
    return InkWell(
      onTap: onCollectAction,
      child: loading
          ? _loadingView()
          : isFollow
              ? Image.asset(
                  'collect_red.png'.commonImgPath,
                  width: 24,
                )
              : Image.asset(
                  'collect_path.png'.commonImgPath,
                  width: 24,
                ),
    );
  }

  //关注样式
  _buildUserFollowView() {
    return InkWell(
      onTap: onFollowEvent,
      child: isFollow
          ? Container(
              alignment: Alignment.center,
              height: 24,
              padding: EdgeInsets.symmetric(horizontal: 12),
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(12),
                color: Colors.white.withOpacity(.05),
              ),
              child: Row(
                children: [
                  loading ? _loadingView() : Icon(
                    Icons.check,
                    size: 14,
                    color: Color(0xff989898),
                  ),
                  4.sizeBoxW,
                  Text(
                    '关注',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: Color(0xff989898)),
                  ),
                ],
              ),
            )
          : Container(
              height: 24,
              padding: EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(
                // border: Border.all(color: widget.borderColor ?? AppColors.primaryHighColor, width: 1),
                color: Color(0xFFE1351F),
                borderRadius: BorderRadius.circular(4),
              ),
              child: Row(
                children: [
                  loading ? _loadingView() : Icon(
                    Icons.add,
                    size: 14,
                    color: Color(0xffffffff),
                  ),
                  4.sizeBoxW,
                  Text(
                    '关注',
                    style: TextStyle(fontSize: 12, fontWeight: FontWeight.w500, color: Colors.white),
                  ),
                ],
              ),
            ),
    );
  }

  _buildNovalCollect() {
    return InkWell(
        onTap: onCollectAction,
        child: loading
            ? _loadingView()
            : Container(
                width: 62,
                height: 24,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  color: isFollow ? Color(0xff3D3D3D) : AppColors.actionRed,
                  borderRadius: BorderRadius.circular(3),
                ),
                child: isFollow
                    ? Text(
                        '已收藏',
                        style: textStyle(10, Colors.white, FontWeight.w400),
                      )
                    : Row(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Image.asset(
                            'add_red.png'.commonImgPath,
                            width: 16,
                            color: Colors.white,
                          ),
                          2.sizeBoxW,
                          Text(
                            '收藏',
                            style: textStyle(10, Colors.white, FontWeight.w400),
                          )
                        ],
                      ),
              ));
  }

  Widget _loadingView() {
    return CupertinoActivityIndicator(
      color: Colors.white,
      radius: 8,
    );
  }

  //加入书架
  onCollectAction() {
    isFollow == true ? cancelFollowAction() : addFollowAction();
  }

  //取消收藏
  cancelFollowAction() async {
    if (loading) return;
    setState(() => loading = true);
    final res = await ACGService.mediaBookshelfDelete(mediaId ?? '');
    if (res) {
      widget.successsAction?.call(false);
    }
    loading = false;
    if (mounted) setState(() {});
  }

  addFollowAction() async {
    if (loading) return;
    setState(() => loading = true);
    final res = await ACGService.mediaBookshelfAdd(mediaId ?? '');
    if (res) {
      widget.successsAction?.call(true);
      // isFollow = true;
    }
    loading = false;
    if (mounted) setState(() {});
  }

  //关注声优
  onFollowEvent() async {
    if (loading) return;
    setState(() => loading = true);
    if (widget.followType == FollowEnum.tag) {
      _onCollectEvent();
    } else if (widget.followType == FollowEnum.user) {
      await _onFollowUser();
    } else {
      await _onFollowOther();
    }
    loading = false;
    if (mounted) setState(() {});
  }

  Future _onCollectEvent() async {
    String typeValue = 'tag';
    bool result = await MineService.postCollect(mediaId, typeValue, !isFollow);
    if (result) {
      showToast(isFollow ? '关注成功' : '取消关注');
      widget.successsAction?.call(isFollow);
    }
  }

  Future _onFollowUser() async {
    bool followStatus = !isFollow;
    bool result = await MineService.getFollow(int.tryParse(mediaId ?? ""), followStatus);
    if (result) {
      showToast(followStatus ? '关注成功' : '取消关注');
      widget.successsAction?.call(isFollow);
    }
  }

  Future _onFollowOther() async {
    String type = "actress";
    if (widget.followType == FollowEnum.actress1) {
      type = "actress1";
    } else if (widget.followType == FollowEnum.actress2) {
      type = "actress2";
    } else if (widget.followType == FollowEnum.voiceActor) {
      type = "actress4";
    }
    bool result = await MineService.postCollect(mediaId, type, !isFollow);
    if (result) {
      widget.successsAction?.call(isFollow);
    }
  }
}
